package com.yuntongxun.ecdemo.core;

import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.Events;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.contact.ContactLogic;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * com.yuntongxun.ecdemo.core in ECDemo_Android
 * Created by Jorstin on 2015/3/21.
 */
public class ContactsCache {

    private static ContactsCache instance;

    private ECArrayLists<ECContacts> contacts;
    private ECArrayLists<ECContacts> allContacts;
    private HashMap<String, String> contactNameMap;

    private LoadingTask asyncTask;

    private ContactsCache(){

    }

    public static ContactsCache getInstance() {
        if (instance == null) {
            instance = new ContactsCache();
        }

        return instance;
    }

    private class LoadingTask extends AsyncTask<Intent, Void, Long> {
        ECArrayLists<ECContacts> allContactsList = null;
        ECArrayLists<ECContacts> contactsList = null;

        public LoadingTask() {
        }

        @Override
        protected Long doInBackground(Intent... intents) {
            try {
                LogUtil.d("contatsCache:开始加载联系人");
                //contactList = ContactLogic.getPhoneContacts(CCPAppManager.getContext());
                //contactList = ContactLogic.getContractList(true);
                allContactsList = new ECArrayLists<ECContacts>();
                contactsList = new ECArrayLists<ECContacts>();
                contactNameMap = new HashMap<String, String>();
                ArrayList<ECContacts> tmpList = ContactSqlManager.getAllContacts();
                for(ECContacts c : tmpList) {
                    ContactLogic.pyFormat(c);
                    allContactsList.add(c);
                    if(c.getStatus() >= 0) {
                        contactsList.add(c);
                    }
                    contactNameMap.put(c.getContactid(), c.getNickname());
                }
                ContactLogic.getMobileContactPhoto(allContactsList);
                ContactLogic.getMobileContactPhoto(contactsList);
            } catch (Exception ce) {
                ce.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Long result) {
            if (contactsList != null) {
                //PinyinHelper.release();
                ECArrayLists<ECContacts> oldContacts = contacts;
                contacts = contactsList;
                allContacts = allContactsList;
                //added
                ArrayList<String> phones = new ArrayList<String>();
                for (ECContacts o : contacts) {
                    List<Phone> phoneList = o.getPhoneList();
                    if (phoneList == null) {
                        continue;
                    }
                    for (Phone phone : phoneList) {
                        if (!TextUtils.isEmpty(phone.getPhoneNum()))
                            phones.add(phone.getPhoneNum());
                    }
                }
                String[] array = phones.toArray(new String[]{});
                Intent intent = new Intent(Events.CONTACTS_UPDATED);
                intent.putExtra("array", array);

                CCPAppManager.getContext().sendBroadcast(intent);
            }
        }

        @Override
        protected void onCancelled() {
        }
    }

    public synchronized void load() {
        try {
            if (asyncTask == null) {
                asyncTask = new LoadingTask();
            }
            asyncTask.execute();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void reload() {
        try {
            stop();
            load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            if (asyncTask != null && !asyncTask.isCancelled()) {
                asyncTask.cancel(true);
                asyncTask = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return the contacts
     */
    public synchronized ECArrayLists<ECContacts> getContacts() {
        return contacts;
    }

    public synchronized ECArrayLists<ECContacts> getAllContacts() {
        return allContacts;
    }

    public void delete(String contactId) {
        ContactSqlManager.delete(contactId);
        for(int i = 0; i < contacts.size(); ++i) {
            if(contacts.get(i).getContactid().equals(contactId)) {
                contacts.remove(contacts.get(i));
                break;
            }
        }
        for(int i = 0; i < allContacts.size(); ++i) {
            if(allContacts.get(i).getContactid().equals(contactId)) {
                allContacts.remove(allContacts.get(i));
                break;
            }
        }
        if(contactNameMap.containsKey(contactId)) {
            contactNameMap.remove(contactId);
        }
    }

    public boolean isMyContact(String contactId) {
        return contactNameMap.containsKey(contactId);
    }

    public void clear() {
        contacts.clear();
        allContacts.clear();
        contactNameMap.clear();
    }
}
